package com.btpj.jetpack.http.exception

import android.net.ParseException
import com.google.gson.JsonParseException
import org.json.JSONException
import retrofit2.HttpException
import java.lang.NumberFormatException
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.net.UnknownServiceException
import javax.net.ssl.SSLHandshakeException

/**
 * 异常统一处理
 *
 * @author LTP 2020/7/8
 */
object DealException {

    /**
     * 异常处理
     *
     * @param throwable Throwable
     * @return ResultException
     */
    fun handleException(throwable: Throwable): ResultException {
        return when (throwable) {
            is ResultException -> throwable
            is HttpException -> {
                when (throwable.code()) {
                    ApiResultCode.UNAUTHORIZED,
                    ApiResultCode.FORBIDDEN,// 权限错误，需要实现
                    ApiResultCode.NOT_FOUND -> ResultException(
                        throwable.code().toString(),
                        "网络异常"
                    )
                    ApiResultCode.REQUEST_TIMEOUT,
                    ApiResultCode.GATEWAY_TIMEOUT -> ResultException(
                        throwable.code().toString(),
                        "网络请求超时"
                    )
                    ApiResultCode.INTERNAL_SERVER_ERROR,
                    ApiResultCode.BAD_GATEWAY,
                    ApiResultCode.SERVICE_UNAVAILABLE -> ResultException(
                        throwable.code().toString(),
                        "服务器出错"
                    )
                    else -> ResultException(
                        throwable.code().toString(),
                        "网络异常"
                    )
                }
            }
            is JsonParseException,
            is JSONException,
            is ParseException -> ResultException(ApiResultCode.PARSE_ERROR, "解析错误")
            is SocketException -> ResultException(
                ApiResultCode.REQUEST_TIMEOUT.toString(),
                "网络连接错误，请重试"
            )
            is SocketTimeoutException -> ResultException(
                ApiResultCode.REQUEST_TIMEOUT.toString(),
                "网络连接超时"
            )
            is SSLHandshakeException -> ResultException(
                ApiResultCode.SSL_ERROR,
                "证书验证失败"
            )
            is UnknownHostException,
            is UnknownServiceException -> ResultException(
                ApiResultCode.UNKNOWN_HOST,
                "网络错误，请切换网络重试"
            )
            is NumberFormatException -> ResultException(
                ApiResultCode.UNKNOWN_HOST,
                "数字格式化异常"
            )
            else -> ResultException(
                ApiResultCode.UNKNOWN,
                "未知错误"
            )
        }
    }
}